[Coding046] LeetCode 388

Longest Absolute File Path

Cook 2024.04.14

More coding records

Get the knowledge flowing and circulating! :)

目录

本题收获

题目:388. Longest Absolute File Path

Suppose we have a file system that stores both files and directories. An example of one system is represented in the following picture:

img

Here, we have dir as the only directory in the root. dir contains two subdirectories, subdir1 and subdir2. subdir1 contains a file file1.ext and subdirectory subsubdir1. subdir2 contains a subdirectory subsubdir2, which contains a file file2.ext.

In text form, it looks like this (with ⟶ representing the tab character):

If we were to write this representation in code, it will look like this: "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext". Note that the '\n' and '\t' are the new-line and tab characters.

Every file and directory has a unique absolute path in the file system, which is the order of directories that must be opened to reach the file/directory itself, all concatenated by '/'s. Using the above example, the absolute path to file2.ext is "dir/subdir2/subsubdir2/file2.ext". Each directory name consists of letters, digits, and/or spaces. Each file name is of the form name.extension, where name and extension consist of letters, digits, and/or spaces.

Given a string input representing the file system in the explained format, return the length of the longest absolute path to a file in the abstracted file system. If there is no file in the system, return 0.

Note that the testcases are generated such that the file system is valid and no file or directory name has length 0.

Example 1:

img

Example 2:

img

Example 3:

Constraints:


代码1(配 · 手绘过程图)Wrong

image-20240414111200466

代码解读 | 评价

这段代码囿于“栈”的思维,忽略了明显的提示:文件的树形结构。

虽然用栈可以做出来,但是思维略微复杂。


代码2(配 · 手绘过程图)

image-20240414111854262

代码解读 | 评价

  • 非常巧妙的代码!

  • 利用了树形结构的特点,思路更加清晰。


 

知识点积累 (Java)

  1. HashMap的基本用法(get() & put()

  2. 计算转义字符的个数(巧妙方法):lastIndexOf('\t') + 1

  3. 字符串中是否包括某个字符串的方法:contains()